package com.example.tool.window;

import com.example.tool.entity.ConfigDBEntity;
import com.example.tool.module.ModuleInformation;
import com.example.tool.module.ModuleInputEnum;
import com.example.tool.ui.HToolIcon;
import com.example.tool.ui.HToolViewItem;
import com.example.tool.ui.SwingViewWrapper;
import com.example.tool.utils.ActionToolUtil;
import com.example.tool.utils.FileUtil;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiManager;
import com.intellij.ui.components.JBTextField;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HToolWindowConfigAction extends DumbAwareAction {
  private static final Logger LOG = Logger.getInstance(HToolWindowConfigAction.class);

  public HToolWindowConfigAction() {
    super(ModuleInformation.CONFIG_DB, "", HToolIcon.CONFIG);
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    try {
      if (project != null) {
        ConfigDBEntity configDBEntity = ActionToolUtil.getInformationDB(project);
        String[] options = {"MYSQL", "SQLSERVER", "ORACLE"};
        ComboBox<String> comboBox = new ComboBox<>(options);
        JBTextField DBUrl = new JBTextField();
        JBTextField DBUser = new JBTextField();
        JBTextField DBPassword = new JBTextField();
        if (configDBEntity != null) {
          comboBox.setSelectedItem(configDBEntity.getDbType());
          DBUrl.setText(configDBEntity.getDbUrl());
          DBUser.setText(configDBEntity.getDbUser());
          DBPassword.setText(configDBEntity.getDbPassword());
        } else {
          DBUrl.setText("jdbc:mysql://localhost:3306/v3x");
        }
        comboBox.addActionListener(e1 -> {
          String selectedType = (String) comboBox.getSelectedItem();
          if (selectedType != null) {
            switch (selectedType) {
              case "MYSQL" -> DBUrl.setText("jdbc:mysql://localhost:3306/v3x");
              case "SQLSERVER" -> DBUrl.setText("jdbc:sqlserver://localhost:1433;DatabaseName=v3x");
              case "ORACLE" -> DBUrl.setText("jdbc:oracle:thin:@localhost:1521:orcl");
              default -> {
              }
            }
          }
        });
        List<HToolViewItem<?>> hToolViewItems = new ArrayList<>();
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.DB_TYPE, comboBox));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.DB_URL, DBUrl, true));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.DB_USER, DBUser));
        hToolViewItems.add(new HToolViewItem<>(ModuleInputEnum.DB_PASSWORD, DBPassword));
        SwingViewWrapper configDialogWrapper = new SwingViewWrapper(project, ModuleInformation.CONFIG_INFO, hToolViewItems, true);
        if (configDialogWrapper.showAndGet()) {
          Map<ModuleInputEnum, String> values = configDialogWrapper.getValues();
          exec(project, values);
        }
      }
    } catch (Exception ex) {
      String text = getTemplatePresentation().getText();
      String textParse = ModuleInformation.textParse(ModuleInformation.OPEN_ACTION_MSG, text);
      LOG.info(textParse + ex.getMessage());
      ActionToolUtil.showNotification(project, NotificationType.ERROR, textParse);
    }
  }

  private void exec(Project project, Map<ModuleInputEnum, String> values) {
    Application application = ApplicationManager.getApplication();
    application.runWriteAction(() -> {
      try {
        PsiManager psiManager = PsiManager.getInstance(project);
        LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
        String basePath = project.getBasePath();
        if (basePath != null) {
          Path path = Path.of(basePath, ".idea");
          VirtualFile fileByNioFile = localFileSystem.findFileByNioFile(path);
          if (fileByNioFile != null) {
            fileByNioFile.refresh(false, true);
            PsiDirectory psiBaseDir = psiManager.findDirectory(fileByNioFile);
            if (psiBaseDir == null) {
              ActionToolUtil.showSetting(project);
              return;
            }
            String dbType = values.get(ModuleInputEnum.DB_TYPE);
            String dbUrl = values.get(ModuleInputEnum.DB_URL);
            String dbUser = values.get(ModuleInputEnum.DB_USER);
            String dbPassword = values.get(ModuleInputEnum.DB_PASSWORD);
            ConfigDBEntity configDBEntity = new ConfigDBEntity(dbType, dbUrl, dbUser, dbPassword);
            FileUtil.createOther(project, psiBaseDir, ModuleInformation.MODULE_CONFIG_DB, configDBEntity.finalResult());
          }
        }
      } catch (Exception e) {
        LOG.info(e.getMessage(), e);
      }
    });
  }
}
